package com.jt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.mapper.MenuMapper;
import com.jt.mapper.RoleAndMenuMapper;
import com.jt.mapper.RoleMapper;
import com.jt.pojo.Menu;
import com.jt.pojo.Role;
import com.jt.pojo.Role_Menu;
import com.jt.service.RoleService;
import com.jt.utils.MenuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleAndMenuMapper roleAndMenuMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private MenuUtils menuUtils;

    @Override
    public Role selectById(String roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public List<String> selectRouterIdListByRoleId(String roleId) {
        return roleMapper.selectRouterIdListByRoleId(roleId);
    }

    @Override
    public List<Role> getRoleList() {
        return roleMapper.selectList(null);
    }

    @Override
    public boolean insertRole(Role role) {
        return roleMapper.insert(role) > 0 ? true : false;
    }

    @Override
    public List<Menu> selectMenuListByRoleId(String roleId) {
        List<Role_Menu> Role_MenuList = roleAndMenuMapper.selectList(new QueryWrapper<Role_Menu>().eq("roleId", roleId));
        List<Menu> menuAndChildrenMenu=null;
        if (!CollectionUtils.isEmpty(Role_MenuList)){
            List<String> menuIds = Role_MenuList.stream().map(Role_Menu::getMenuId).collect(Collectors.toList());
            List<Menu> MenuList = menuMapper.selectList(new QueryWrapper<Menu>().in("id", menuIds));
            List<Menu> allList = MenuList.stream().filter(item -> !item.getType().equals("2")).collect(Collectors.toList());
            menuAndChildrenMenu = menuUtils.getMenuAndChildrenMenu(allList);
        }
        return menuAndChildrenMenu;
    }

}
